package com.ywb.edugui.controller;

import com.ywb.edugui.dao.OssDao;
import com.ywb.edugui.dao.TeacherDao;
import com.ywb.edugui.dao.facotry.DaoFactory;
import com.ywb.edugui.entity.Teacher;
import com.ywb.edugui.entity.vo.TeacherExcel;
import com.ywb.edugui.entity.vo.TeacherQuery;
import com.ywb.edugui.utils.ExcelUtils;
import com.ywb.edugui.utils.ImageUtils;
import com.ywb.edugui.utils.R;
import com.ywb.edugui.view.MainView;
import com.ywb.edugui.view.teacher.TeacherAddOrUpdatePanel;
import com.ywb.edugui.view.teacher.TeacherListPanel;
import sun.applet.Main;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author ywb
 * Teacher控制器,控制TeacherList和TeacherAddOrUpdate的事件处理
 */
public class TeacherController {
    private TeacherDao teacherDao = DaoFactory.getTeacherDao();
    private OssDao ossDao = DaoFactory.getOssDao();
    private Container teacherView;

    public TeacherController(Container view){
        teacherView = view;
    }

    public void avatarSelect(){
        TeacherAddOrUpdatePanel view = (TeacherAddOrUpdatePanel) teacherView;
        //        创建文件选择器并默认初始打开为项目根目录
        JFileChooser chooser = new JFileChooser(new File("./edugui/src/main"));
//        设置被选中的文件类型为只有Files
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
//        设置过滤文件类型
        chooser.setFileFilter(new FileNameExtensionFilter("仅接受图片文件","jpg","png","jpeg"));
//        打开文件选择对话框,当返回值为Approve_Option时
        if(chooser.showOpenDialog(teacherView) == JFileChooser.APPROVE_OPTION){
//            获得被选中的文件
            File imageFile = chooser.getSelectedFile();
//            判断: 文件大小是否过大
            if((imageFile.length() / (1024 * 1024)) > 1){
                JOptionPane.showMessageDialog(teacherView, "头像图片过大！", "main.teacheradd", JOptionPane.WARNING_MESSAGE);
            }
//            获取文件名称,用于上传
            view.setSelectedFileName(imageFile.getName());
//            根据文件生成IamgeIcon
            ImageIcon avatarIcon = new ImageIcon(imageFile.getAbsolutePath());
//            判断图片的大小是否过大
            if(avatarIcon.getIconHeight() > 100 || avatarIcon.getIconWidth() > 100 ){
//                使用Utils剪辑工具进行缩放
                view.setAvatarImage(ImageUtils.zoom(imageFile.getAbsolutePath()));
                avatarIcon = new ImageIcon(view.getAvatarImage());
            }
//            获得被选中文件的绝对路径,作为参数封装为ImageIcon返回到jlAvatar标签中显示出来
            view.getJlAvatar().setIcon(avatarIcon);
            view.setUploadFlag(true);
        }
    }

    public void saveOrUpdate(){
        TeacherAddOrUpdatePanel view = (TeacherAddOrUpdatePanel) teacherView;
        teacherView.setCursor(new Cursor(Cursor.WAIT_CURSOR));

        if(view.getUpdateTeacher() == null) {
//            获取教师框的数据
            String teacherName = view.getTfTeacherName().getText();
            int teacherLevel = view.getCbTeacherLevel().getSelectedItem().toString().equals("初级教师") ? 1 : 2;
            String teacherIntro = view.getTfTeacherIntro().getText();

            String teacherAvatar = "";
//            如果用户点击了图片选择器则上传头像，否则avatar属性值为空
            if(view.isUploadFlag()) {
                teacherAvatar = ossDao.upload(ImageUtils.bufferedImageToInputStream(view.getAvatarImage()), view.getSelectedFileName());
            }
            Teacher teacher = new Teacher(teacherName, teacherLevel, teacherIntro, teacherAvatar);
//            如果教师返回值<0则数据库上传失败，弹出提示信息
            if (teacherDao.add(teacher) < 1) {
                JOptionPane.showMessageDialog(view, "添加失败!", "main.teacheradd", JOptionPane.WARNING_MESSAGE);
                return;
            }
            JOptionPane.showMessageDialog(view, "添加成功!");

        }else{
            String teacherName = view.getTfTeacherName().getText();
            int teacherLevel = view.getCbTeacherLevel().getSelectedItem().toString().equals("初级教师") ? 1 : 2;
            String teacherIntro = view.getTfTeacherIntro().getText();
            if(teacherName != null){
                view.getUpdateTeacher().setName(teacherName);
            }
            if(teacherLevel != 0){
                view.getUpdateTeacher().setLevel(teacherLevel);
            }
            if(teacherIntro != null){
                view.getUpdateTeacher().setIntro(teacherIntro);
            }
//            如果用户点击了图片选择器则上传头像，否则avatar属性值为空
            if(view.isUploadFlag()) {
                 view.getUpdateTeacher().setAvatar(ossDao.upload(ImageUtils.bufferedImageToInputStream(view.getAvatarImage()), view.getSelectedFileName()));
            }
            if (teacherDao.update(view.getUpdateTeacher()) < 1) {
                JOptionPane.showMessageDialog(view, "更新失败!", "TeacherAddOrUpdatePanel", JOptionPane.WARNING_MESSAGE);
                return;
            }
            JOptionPane.showMessageDialog(view, "修改成功!");
        }
//         重置面板数据
        view.setUpdateTeacher(null);
        view.setUploadFlag(false);
//        关闭当前选项卡并切换到教师列表选项卡
        MainView.changeChildrenPanel("教师列表", new TeacherListPanel(), true);
        teacherView.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

    }

    public R update(){
        TeacherListPanel view = (TeacherListPanel) teacherView;

        String teacherId = (String)view.getJTable1().getValueAt(view.getJTable1().getSelectedRow(), 0);
        Teacher teacher = teacherDao.getOne(teacherId);
        JPanel teacherUpdatePanel = new TeacherAddOrUpdatePanel(teacher);
//        获得mainView中的childrenPanel，进行切换panel
        MainView.changeChildrenPanel(MainView.getBundle().getString("teacher.update"),teacherUpdatePanel, true);
        return null;
    }

    public R delete(){
        TeacherListPanel view = (TeacherListPanel) teacherView;
        //        JOptionPane.Option有WARNING, ERROR, INFORMATION, QUESTION, PLAIN
//        如果点击的不是确认则退出该方法
        if(JOptionPane.YES_OPTION != JOptionPane.showConfirmDialog(teacherView, "确认要删除该数据吗","删除教师", JOptionPane.WARNING_MESSAGE )){
            return null;
        }
        //        获取选中单元格的数据的第一列id值并转化成string类型
        String teacherId = (String)view.getJTable1().getValueAt(view.getJTable1().getSelectedRow(), 0);
        int result = teacherDao.delete(teacherId);
        JOptionPane.showMessageDialog(teacherView, "成功删除" + result + "条数据");
        return null;
    }

    public R query(){
        TeacherListPanel view = (TeacherListPanel) teacherView;
        //        获取查询框的值封装到teacherQuery中
        String teacherName = view.getTfTeacherName().getText();
        int teacherLevel = ((String)view.getCbTeacherLevel().getSelectedItem()).equals("高级教师") ? 2 : view.getCbTeacherLevel().getSelectedItem().equals("初级教师") ? 1 : 0;
        String teacherIntro = view.getTfTeacherIntro().getText();
        TeacherQuery teacherQuery = new TeacherQuery();
        teacherQuery.setTeacherName(teacherName).setTeacherLevel(teacherLevel).setTeacherIntro(teacherIntro);
//        调用teacherdao的方法根据query查询 返回查询到的list结果
        List<Teacher> listByQuery = teacherDao.list(teacherQuery);
//        将list结果转化为用于表格显示的String[][]类型
        view.changeTable(listToDoubleArray(listByQuery), null);

        return null;
    }

    /**
     * 将list转化为二维数组
     * @param list
     * @return
     */
    private String[][] listToDoubleArray(List<Teacher> list){
        return list.stream().map(teacher -> {
            String[] s = {teacher.getId(), teacher.getName(), teacher.getLevel() == 1 ? "初级教师" : "高级教师", teacher.getIntro(), teacher.getAvatar()};
            return s;
        }).toArray(String[][]::new);
    }

    public R sortList(){
        TeacherListPanel view = (TeacherListPanel) teacherView;

        String sortOrder = (String) view.getCbSortOrder().getSelectedItem();
        String sortCondition = (String) view.getCbSortCondition().getSelectedItem();

        TeacherQuery query = new TeacherQuery();
        query.setTeacherOrder(sortOrder).setTeacherOrderCondition(sortCondition);
        //        调用teacherdao的方法根据query查询 返回查询到的list结果
        List<Teacher> listByQuery = teacherDao.list(query);
//        将list结果转化为用于表格显示的String[][]类型
        view.changeTable(listToDoubleArray(listByQuery), null);
        return null;
    }

    public R exportExcel(){
//        让用户选择需要文件导出的文件夹
        JFileChooser chooser = new JFileChooser(new File("D:" + File.separator));
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//        打开文件选择对话框,当返回值为Approve_Option时
        if(chooser.showSaveDialog(teacherView) != JFileChooser.APPROVE_OPTION) {
            return null;
        }
        teacherView.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        String filepath = chooser.getSelectedFile().getAbsolutePath() + File.separator +"教师列表Excel.xlsx";
//       查询教师转化为TeacherExcel模型然后导出
        List<Teacher> teachers = teacherDao.list();
        List<TeacherExcel> teacherExcels = teachers.stream().map(teacher -> {
            URL url = null;
            try {
                url = new URL(teacher.getAvatar());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            TeacherExcel teacherExcel = new TeacherExcel(teacher.getName(), teacher.getLevel() == 1 ? "初级教师" : "高级教师", teacher.getIntro(), url);
            return teacherExcel;
        }).collect(Collectors.toList());
        ExcelUtils.exportTeacherExcel(filepath, teacherExcels);
        JOptionPane.showMessageDialog(teacherView, "导出成功!!\n文件于" +filepath);
        teacherView.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        try{
            Desktop.getDesktop().open(new File(chooser.getSelectedFile().getAbsolutePath()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }

    public R prePage() {

        return null;
    }

    public R nextPage() {

        return null;
    }

    public void resetList() {
        ((TeacherListPanel) teacherView).getTfTeacherName().setText("");
        ((TeacherListPanel) teacherView).getCbTeacherLevel().setSelectedIndex(0);
        ((TeacherListPanel) teacherView).getTfTeacherIntro().setText("");
        sortList();
    }
}
